﻿using MediatR;
using S.Eartag.Domain.Model;
using S.Eartag.Domain;
using S.Eartag.Read.API.Application.Command.MarkedConditionCommand;
using S.Eartag.Infrastructure.Interface;
using S.Eartag.Infrastructure.Impl;

namespace S.Eartag.Read.API.Application.CommandHandlers.MarkedConditionCommandHandler
{
    public class MarkedConditionGetCommandHandler : IRequestHandler<MarkedConditionGetCommand, PageInfoS<Mark>>
    {
        private readonly IMarkRepository markRepository;

        public MarkedConditionGetCommandHandler(IMarkRepository markRepository)
        {
            this.markRepository = markRepository;
        }

        public async Task<PageInfoS<Mark>> Handle(MarkedConditionGetCommand request, CancellationToken cancellationToken)
        {
            var list = markRepository.All().Result.Where(x=>!x.IsDel).AsQueryable();
            if (!string.IsNullOrEmpty(request.earnumber))
            {
                list = list.Where(x => x.EarNumber.Contains(request.earnumber));
            }
            if (!string.IsNullOrEmpty(request.oldeartag))
            {
                list = list.Where(x => x.OldEarTag.Contains(request.oldeartag));
            }
            if (!string.IsNullOrEmpty(request.neweartag))
            {
                list = list.Where(x => x.NewEarTag.Contains(request.neweartag));
            }

            if (request.reason > 0)
            {
                list = list.Where(x => x.Reason == request.reason);
            }
            if (request.markedCondition > 0)
            {
                list = list.Where(x => x.MarkedCondition == request.markedCondition);
            }

            int totalCount =list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.psize);
            list = list.OrderByDescending(x => x.Id).Skip((request.pindex - 1) * request.psize).Take(request.psize);
            return new PageInfoS<Mark>
            {
                list = list.ToList(),
                totalCount = totalCount,
                pageCount = pageCount
            };
        }
    }
}
